<template>
  <div :bordered="false">
    <a-row :gutter="16">
      <a-col :span="8" style="text-align: left;">
        <a-button
          type="primary"
          @click="
            showAddModal = true
            isEdit = false
          "
          >添加用户</a-button
        >
      </a-col>
    </a-row>

    <a-table
      class="width:100%;"
      :columns="columns"
      :data-source="filteredUsers"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template slot="action" slot-scope="text, record">
        <a @click="edit(record)">编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm title="确定要删除该用户吗？" @confirm="() => deleteRecord(record.id)">
          <a>删除</a>
        </a-popconfirm>
      </template>
    </a-table>

    <a-modal v-model="showAddModal" :title="isEdit ? '编辑' : '新增'" @ok="handleAdd" @cancel="handleCancel">
      <a-form :form="form">
        <a-form-item label="类型" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-radio-group
            v-decorator="['type', { initialValue: '1', rules: [{ required: true, message: '请选择类型！' }] }]"
          >
            <a-radio value="1">单位法定代表人信息</a-radio>
            <a-radio value="2">委托人信息</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="姓名" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userName', { rules: [{ required: true, message: '请输入姓名！' }] }]" />
        </a-form-item>
        <a-form-item label="性别" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-radio-group
            v-decorator="['userSex', { initialValue: '1', rules: [{ required: true, message: '请选择性别！' }] }]"
          >
            <a-radio value="1">男</a-radio>
            <a-radio value="0">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="身份证号" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userCard', { rules: [{ required: false, message: '请输入身份证号！' }] }]" />
        </a-form-item>
        <a-form-item label="所在部门" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userDept', { rules: [{ required: false, message: '请输入所在部门！' }] }]" />
        </a-form-item>
        <a-form-item label="职务" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userJob', { rules: [{ required: false, message: '请输入所在部门！' }] }]" />
        </a-form-item>
        <a-form-item label="职称" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userTitle', { rules: [{ required: false, message: '请输入所在部门！' }] }]" />
        </a-form-item>
        <a-form-item label="电话号码" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userTel', { rules: [{ required: false, message: '请输入所在部门！' }] }]" />
        </a-form-item>
        <a-form-item label="传真号码" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userFax', { rules: [{ required: false, message: '请输入所在部门！' }] }]" />
        </a-form-item>
        <a-form-item label="手机号码" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userPhone', { rules: [{ required: true, message: '请输入手机号！' }] }]" />
        </a-form-item>
        <a-form-item label="电子邮箱" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userEmail', { rules: [{ required: false, message: '请输入邮箱！' }] }]" />
        </a-form-item>
        <a-form-item label="负责业务" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-input v-decorator="['userBisness', { rules: [{ required: false, message: '请输入负责业务！' }] }]" />
        </a-form-item>
        <a-form-item label="备注" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16 }">
          <a-textarea
            v-decorator="['remark', { rules: [{ required: false, message: '请输入备注！' }] }]"
            placeholder="请输入备注！"
            :autosize="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { Table, Form } from 'ant-design-vue'
import { axios } from '@/utils/request'
import { mapGetters } from 'vuex'
import { mixin } from 'vuedraggable'
import { tableImgMixin, tableMixin } from './mixin'

const { Column } = Table
const { Item: FormItem } = Form

export default {
  name: 'UserConcat',
  components: {},
  props: {
    canFix: {
      type: Boolean,
    },
    // 基本类型检查 (`null` 和 `undefined` 会通过任何类型验证)
    legalCode: String,
  },
  mixins: [tableImgMixin, tableMixin],
  data() {
    return {
      isEdit: false,
      searchText: '',
      showAddModal: false,
      showEditModal: false,
      users: [],
      filteredUsers: [],
      currentRow: null,
      type: '1',
      form: this.$form.createForm(this, { name: 'user' }),
    }
  },

  computed: {
    ...mapGetters(['userInfo']),
    columns() {
      return [
        {
          title: '联系人类型',
          dataIndex: 'type',
          key: 'type',
          customRender: text => (text === '1' ? '法人' : '联系人'),
        },
        { title: '姓名', dataIndex: 'userName', key: 'userName' },
        { title: '邮箱', dataIndex: 'userEmail', key: 'userEmail' },
        { title: '手机', dataIndex: 'userPhone', key: 'userPhone' },

        { title: '负责业务', dataIndex: 'userBisness', key: 'userBisness' },
        { title: '所在部门', dataIndex: 'userDept', key: 'userDept' },
        { title: '身份证号', dataIndex: 'userCard', key: 'userCard' },
        { title: '备注', dataIndex: 'remark', key: 'remark' },
        { title: '操作', key: 'action', scopedSlots: { customRender: 'action' } },
      ]
    },
  },
  methods: {
    async getData() {
      try {
        const response = await axios.get('/register/subjectLegalUser/list', {
          params: { legalCode: this.legalCode, pageSize: this.pagination.pageSize, pageNo: this.pagination.current },
        })
        this.users = response.result.records
        this.filteredUsers = response.result.records
        this.pagination.total = response.result.total
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    },

    edit(record) {
      this.isEdit = true
      this.currentRow = record
      this.showAddModal = true
      this.$nextTick(() => {
        this.form.setFieldsValue(record)
      })
    },
    deleteRecord(id) {
      this.$http
        .delete(`/register/subjectLegalUser/delete?id=${id}`)
        .then(() => {
          this.getData()
        })
        .catch(error => {
          console.error('删除用户失败:', error)
        })
    },
    handleAdd() {
      if (this.isEdit) {
        this.handleEdit()
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          values.legalCode = this.legalCode
          values.type = this.type
          axios
            .post('/register/subjectLegalUser/add', values)
            .then(() => {
              this.showAddModal = false
              this.getData()
            })
            .catch(error => {
              console.error('添加用户失败:', error)
            })
        }
      })
    },
    handleEdit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          values.legalCode = this.userInfo.legalCode
          values.id = this.currentRow.id
          this.$http
            .put(`/register/subjectLegalUser/edit`, values)
            .then(() => {
              this.showAddModal = false
              this.getData()
            })
            .catch(error => {
              console.error('更新用户失败:', error)
            })
        }
      })
    },
    handleCancel() {
      this.showAddModal = false
      this.showEditModal = false
      this.form.resetFields()
    },
  },
  created() {
    this.getData()
  },
}
</script>

<style scoped>
/* Add your styles here */
</style>
